<template>
  <div>
    <div id="map-container" style="width: 100%; height: 500px;"></div>
    <div v-if="!!startPoint.length" v-show="isShow" id="panel"
         style="width: 100%; height: 200px; overflow: auto;"></div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'

export default {
  props: {
    startPoint: {
      type: Array,
      default: () => [116.397428, 39.90923],
    },
    endPoint: {
      type: Array,
      default: () => [116.407396, 39.904199],
    },
    polyline: {
      type: Array,
      default: () => []
    },
    zoom: {
      type: Number,
      default: 13,
    },
    lng: {
      type: String,
      default: 109.470962,
    },
    lat: {
      type: String,
      default: 34.520632,
    },
    viewMode: {
      type: String,
      default: '3D',
    },
    policy: {
      type: String,
      default: 'LEAST_TIME',
    },
    isShow: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    polyline: {
      handler(val) {
        if (!!val.length) {
          this.$nextTick(() => {
            setTimeout(() => {
              this.map.clearMap();
              this.addPolyline(val);
            }, 500); // 延迟执行保证地图已加载
          });
        }
      },
      deep: true,
      immediate: true
    },
    startPoint() {
      this.drawRoute();
    },
    endPoint() {
      this.drawRoute();
    },
    zoom(val) {
      if (this.map) {
        this.map.setZoom(val);
      }
    },
    lng(val) {
      if (this.map) {
        this.map.setCenter([val, this.lat]);
      }
    },
    lat(val) {
      if (this.map) {
        this.map.setCenter([this.lng, val]);
      }
    },
    viewMode() {
      this.initMap()
    },
    policy: {
      handler(val) {
        console.log('this.driving', this.driving)
        if (this.driving) {
          this.driving.setPolicy(AMap.DrivingPolicy[val]);
          this.drawRoute();
        }
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    return {
      map: null,
      driving: null,
      markers: {}
    };
  },
  mounted() {
    this.initMap();
  },
  methods: {
    async initMap() {
      let _this = this;
      AMapLoader.reset()
      AMapLoader.load({
        key: '50732c931c229965d9e9ecd4be09394c',
        version: "1.4.15",
        plugins: [
          "AMap.ToolBar",
          "AMap.Scale",
          "AMap.HawkEye",
          "AMap.MapType",
          "AMap.Geolocation",
          "AMap.ControlBar",
          "AMap.MoveAnimation",
          "AMap.Driving",
          "AMap.Geocoder",
          "AMap.PlaceSearch",
          "AMap.Marker",
          "AMap.Polyline"
        ],
      })
          .then((AMap) => {
            const props = {
              zoom: _this.zoom,
              center: [_this.lng, _this.lat],
              viewMode: _this.viewMode,
            }
            _this.map = new AMap.Map('map-container', props);
            console.log(' _this.map', _this.map)
            _this.map.on('click', _this.handleClick); // 地图点击事件 可获取经纬度等信息
            AMap.plugin('AMap.Driving', () => {
              _this.driving = new AMap.Driving({
                policy: AMap.DrivingPolicy[_this.policy],
                map: _this.map,
                panel: 'panel',
              });
            });
            _this.initScaleTools(_this.map, false, false)
          })
          .catch((error) => {
            console.error("Failed to load AMap:", error);
          });
    },
    addPolyline(points) {
      // 遍历每个 polyline 数据项
      points.forEach((item, index) => {
        const pointsList = [];

        // 提取当前项的坐标点列表
        if (item.经纬度列表 && Array.isArray(item.经纬度列表)) {
          item.经纬度列表.forEach(v => {
            if (v.坐标点 && Array.isArray(v.坐标点) && v.坐标点.length >= 2) {
              pointsList.push(v.坐标点);
            }
          });
        }
        const routeKey = `route_${index}`;
        this.drawMarkers(pointsList, routeKey);
        if (pointsList.length > 0) {
          // 创建 Polyline 实例
          const polyline = new AMap.Polyline({
            path: pointsList,
            strokeColor: item.颜色,
            strokeWeight: item.宽度,
            strokeOpacity: 0.5,
            isOutline: item.是否虚线,
            outlineColor: item.边框颜色,
            outlineWidth: item.边框宽度,
          });

          // 添加到地图
          this.map.add(polyline);

          // 设置中心为第一个点
          this.map.setCenter(pointsList[0]);
        }
      });
    },
    handleClick(e) {
      console.log('e', e)
    },
    drawRoute() {
      if (!this.driving && !!this.startPoint.length) {
        console.error("Driving plugin not initialized");
        return;
      }
      this.driving.clear();
      this.driving.search(
          new AMap.LngLat(...this.startPoint),
          new AMap.LngLat(...this.endPoint),
          (status, result) => {
            if (status === 'complete') {
              console.log('路线规划完成', result);
            } else {
              console.error('路线规划失败', result);
            }
          }
      );
    },
    drawMarkers(val, key = 'default') {
      if (!key) key = 'default';

      // 如果有旧的 markers，先移除
      if (this.markers[key]) {
        this.removeMarker(this.map, this.markers[key]);
      }

      if (val.length) {
        const newMarkers = this.addMarker(this.map, val, (e) => {
          console.log('marker clicked', e);
        });

        this.markers[key] = newMarkers;
      } else {
        this.markers[key] = [];
      }
    },

    addMarker(map, markers, callback) {
      if (!markers || !markers.length) return []; // 确保 markers 不为空
      var markerInstances = markers.map(e => {
        var mark = new AMap.Marker({
          position: [e[0], e[1]],
        });
        // 使用 setContent 替代 formatter
    //     mark.setContent(`<div style="background: #fff; padding: 10px; border: 1px solid #ccc;">
    //   ${e[2]}
    // </div>`);
        if (callback) mark.on('click', callback);
        return mark;
      });
      map.add(markerInstances); // 确保参数是标记数组
      return markerInstances;
    }
    ,
    removeMarker(map, markers) {
      if (!markers || !markers.length) return; // 确保 markers 不为空
      map.remove(markers); // 确保参数是标记数组
    }
    ,
    initScaleTools(map, noScale, noToolBar) {
      if (!noScale) {
        map.plugin(["AMap.Scale"], function () {
          var scale = new AMap.Scale();
          map.addControl(scale);
        });
      }
      if (!noToolBar) {
        map.plugin(["AMap.ToolBar"], function () {
          var tool = new AMap.ToolBar();
          map.addControl(tool);
        });
      }
    },
    searchByKeyword(map, callback, otherProps, keyword) {
      map.clearMap()
      AMap.plugin(['AMap.PlaceSearch'], function () {
        var placeSearch = new AMap.PlaceSearch({
          map: map,
          ...otherProps,
        })
        placeSearch.search(keyword, callback)
      })
    }
  }
}
;
</script>
